package com.java.mvc;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        final String path = config.getInitParameter("ContentConfigLocation");
        HandlerMapping.init(DispatcherServlet.class.getClassLoader().getResourceAsStream(path));
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final String uri = req.getRequestURI();
        final HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(uri);
        if (mvcMapping == null) {
            resp.sendError(404, "您访问的页面不存在");
            return;
        }
        final Object o = mvcMapping.getObject();
        final Method m = mvcMapping.getMethod();
        final String result;
        try {
            result = (String) m.invoke(o, req, resp);
            switch (mvcMapping.getType()) {
                case Text:
                    resp.getWriter().write(result);
                    break;
                case View:
                    resp.sendRedirect(result);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            resp.sendError(500, "服务器 mvc 映射时发生了一个错误，请联系管理员解决。\n错误信息：" + e.getMessage());
        }
    }
}
